//申请成为入住商家
var basePage = require('../../../common/BasePage');
var util = require('../../../utils/util');
Page({
    behaviors: [basePage],
    /**
     * 页面的初始数据
     */
    data: {
        catArr: [],
        /**仓库列表 */
        areaData: [],
        /**当前选中的仓库 */
        warehouse: {
            wh_id: 1, //仓库id
            title: '选择仓库分仓',
        },
        /**选中的分类id数组 */
        catIdArr: [],
        /**显示选中的分类内容 */
        catVal: "请选择品种分类或者产品",

        /**
         * 是否显示分类列表弹窗
         */
        showCatList: false,
        /**是否显示仓库列表 */
        showArea: false,
        /**公司名称 */
        com_title: '',
        /**联系人 */
        contact: '',
        /**电话 */
        mobile: '',
        /**是否有基地[0:没有基地,1:有*/
        have_base: 0,
        /**授权类型[1:产品,0:分类*/
        have_type: 1,
        /**身份证正面 */
        id_photo_front: {
            /**完整图片路径 */
            url: '/assets/zhengmian.png',
            /**后台地址 */
            photo: '',
            /**''未选择;loading 上传中;error 上传失败;ok 上传成功 */
            state: '',
        },
        /**身份证反面 */
        id_photo_back: {
            /**完整图片路径 */
            url: '/assets/fanmian.png',
            /**后台地址 */
            photo: '',
            /**''未选择;loading 上传中;error 上传失败;ok 上传成功 */
            state: '',
        },

        /**营业执照 */
        account_photo: {
            /**完整图片路径 */
            url: '/assets/photo.png',
            /**后台地址 */
            photo: '',
            /**''未选择;loading 上传中;error 上传失败;ok 上传成功 */
            state: '',
        },
        /**基地视频地址 */
        base_video: {
            /**上传图标 */
            url: '/assets/photo.png',
            /**后台地址 */
            video: '',
            /**''未选择;loading 上传中;error 上传失败;ok 上传成功 */
            state: '',
        },
        /**是否同意协议 */
        agree: false,
        // 供应租金
        totalPrice: 0,
        tenancy_status: 1, //开启租赁收费[0:未开启,1:已开启]

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.getTenancy()
        this.getPayType(1)
        let catArr = getApp().globalData.cateArr;
        let areaData = getApp().globalData.areaData;
        let updateData = {};
        if (!catArr) { //没有分类缓存
            this.request({
                url: this.data.host + '/home/product/cate?limit=1000'
            }, this.get_cate_ok);
        } else {
            updateData.catArr = catArr
        }
        if (areaData && areaData.length) {
            updateData.areaData = areaData;
            areaData.map(function (value) {
                value.text = value.title
            })
        } else {
            this.request({
                url: this.data.host + '/home/index/warehouse?limit=100'
            }, res => {

                console.log("areaData", res.data)
                if (res.data.length) {
                    res.data.map(function (value) {
                        value.text = value.title
                    })
                    getApp().globalData.areaData = res.data;
                }
                this.setData({
                    areaData: res.data
                });
            });
        }
        updateData.areaData || updateData.catArr ? this.setData(updateData) : '';
    },
    //渲染分类数据
    get_cate_ok(res) {
        // console.log("get_cate_ok", res);
        getApp().globalData.cateArr = res.data;
        this.setData({
            catArr: res.data
        })
    },
    /**
     * 打开分类列表
     */
    open_catList() {
        //产品授权跳转
        if (this.data.have_type == 1) {
            let that = this;
            wx.navigateTo({
                url: '/pages/cls/applyShop/shopGoods/choose?wh_id=' + this.data.warehouse.wh_id,
                events: {
                    choose_goods: function (data) {
                        console.log("选择产品", data);
                        let goodsList = data
                        let totalPrice = 0
                        let valArr = []
                        let catIdArr = []

                        goodsList.map(val => {
                            valArr.push(val.product_name);
                            catIdArr.push(val.product_id);
                            totalPrice = totalPrice + Number(val.tenancy_amount)
                        })
                        that.setData({
                            totalPrice: totalPrice,
                            catIdArr: catIdArr,
                            catVal: valArr.join(',')
                        })
                    }
                }
            })
        } else {
            this.setData({
                showCatList: true
            })
        }

    },
    /**打开仓库列表 */
    open_wh() {
        this.setData({
            showArea: true
        })
    },
    /**
     * 分类选择事件
     */
    cat_change(e) {
        // console.log("cat_change",e)
        let index = e.mark.index;
        let catArr = this.data.catArr;
        catArr[index].selected = !catArr[index].selected;
        this.setData({
            catArr
        });
        
    },
    /**
     * 选中仓库
     * @param {event} e 
     */
    choose_wh(e) {
        console.log("choose_wh", e);
        this.setData({
            warehouse: this.data.areaData[e.detail.index],
            showArea: false
        })
    },
    confirm_wh(e){
      console.log("confirm_wh", e);
      this.setData({
        warehouse: this.data.areaData[e.detail.index],
        showArea: false
    })
    },
    cance_wh(){
      this.setData({
        showArea:false
      })
    },  
    /**
     * 确认选中的分类
     */
    sure_cat() {
        // let catArr=this.data.catArr;
        let catIdArr = [];
        let valArr = [];
        let totalPrice = 0
        this.data.catArr.map(function (value) {
            if (value.selected) {
                catIdArr.push(value.cate_id);
                valArr.push(value.title);
                totalPrice = totalPrice + Number(value.tenancy_amount)
            }
        })
        if (!catIdArr.length) {
            return wx.showToast({
                icon: 'none',
                title: '请选择品种',
            })
        }
        this.setData({
            catIdArr,
            totalPrice: totalPrice,
            catVal: valArr.join(','),
            showCatList: false
        })
    },
    /**是否有基地状态切换 */
    base_change(e) {
        let val = parseInt(e.currentTarget.dataset.val);
        if (val == this.data.have_base) {
            return
        }
        this.setData({
            have_base: val
        });
        // console.log(this.data.have_base)
    },
    agree_change(e) {
        this.setData({
            agree: !this.data.agree
        })
    },
    /**上传身份证正反面,营业执照 */
    img_upload(e) {
        let that = this;
        /**上传图片的对象 */
        let img = e.currentTarget.dataset.img;
        wx.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['album', 'camera'],
            success(imgRes) {
                // tempFilePath可以作为img标签的src属性显示图片
                const tempFilePaths = imgRes.tempFilePaths;
                console.log("tempFilePaths", tempFilePaths);
                let photo = {}; //用于更新视图诗句
                let id_photo_front = photo[img] = that.data[img];
                id_photo_front.url = tempFilePaths[0];
                id_photo_front.state = "loading";
                console.log("photo", photo)
                that.setData(photo)
                wx.uploadFile({
                    filePath: tempFilePaths[0],
                    name: 'image',
                    url: that.data.host + '/home/upload/image',
                    formData: {
                        from: 'verify'
                    },
                    success(res) {
                        id_photo_front.state = "error";
                        // id_photo_front.photo='';
                        // console.log("home/upload/image", res);
                        if (res.statusCode != 200) {
                            return wx.showModal({
                                showCancel: false,
                                content: res.errMsg || '上传失败',
                            })
                        }
                        let resObj = JSON.parse(res.data);
                        if (resObj.code) {
                            return wx.showToast({
                                title: resObj.msg,
                                icon: 'none'
                            })
                        }
                        id_photo_front.state = "ok";
                        id_photo_front.photo = resObj.data.path;

                    },
                    fail() {
                        id_photo_front.state = "error";
                        wx.showModal({
                            showCancel: false,
                            content: '上传接口异常',
                        })
                    },
                    complete() {
                        that.setData(photo)
                    }
                });
            },
            fail(e) {
                wx.showToast({
                    title: e.errMsg || '调用微信文件失败',
                    icon: 'none'
                })
                // console.log(e);
            }
        })
    },
    /**上传基地视频 */
    read_video(event) {
        const {
            file
        } = event.detail;
        console.log("file", file)
    },
    video_upload(e) {
        // wx.chooseMedia({
        //   count: 9,
        //   mediaType: ['image','video'],
        //   sourceType: ['album', 'camera'],
        //   maxDuration: 30,
        //   camera: 'back',
        //   success(res) {
        //     console.log(res.tempFiles.tempFilePath)
        //     console.log(res.tempFiles.size)
        //   }
        // })
        let that = this;
        /**上传图片的对象 */
        let img = e.currentTarget.dataset.img;
        wx.chooseMedia({
            count: 1,
            mediaType: ['video'],
            sourceType: ['album', 'camera'],
            maxDuration: 60,
            camera: 'back',
            success(imgRes) {
                console.log("imgRes", imgRes)
                // tempFilePath可以作为img标签的src属性显示图片
                const tempFilePaths = imgRes.tempFiles[0].tempFilePath;

                console.log("tempFilePaths", tempFilePaths);
                let photo = {}; //用于更新视图诗句
                let id_photo_front = photo[img] = that.data[img];
                id_photo_front.url = imgRes.tempFiles[0].thumbTempFilePath;
                id_photo_front.state = "loading";
                // console.log("photo",photo)
                that.setData(photo)
                wx.uploadFile({
                    filePath: tempFilePaths,
                    name: 'file',
                    url: that.data.host + '/home/upload/video',
                    formData: {
                        from: 'verify'
                    },
                    success(res) {
                        id_photo_front.state = "error";
                        // id_photo_front.photo='';
                        // console.log("home/upload/image", res);
                        if (res.statusCode != 200) {
                            return wx.showModal({
                                showCancel: false,
                                content: res.errMsg || '上传失败',
                            })
                        }
                        let resObj = JSON.parse(res.data);
                        if (resObj.code) {
                            return wx.showToast({
                                title: resObj.msg,
                                icon: 'none'
                            })
                        }
                        id_photo_front.state = "ok";
                        id_photo_front.video = resObj.data.path;

                    },
                    fail() {
                        id_photo_front.state = "error";
                        wx.showModal({
                            showCancel: false,
                            content: '上传接口异常',
                        })
                    },
                    complete() {
                        that.setData(photo)
                    }
                });
            },
            fail(e) {
                wx.showToast({
                    title: e.errMsg || '调用微信文件失败',
                    icon: 'none'
                })
                // console.log(e);
            }
        })
    },
    /**
     * 提交申请
     */
    submitBtn_click() {
        if (!this.data.agree) {
            return wx.showToast({
                title: '请同意协议',
                icon: 'none'
            })
        }
        let errorTip = "";
        let data = this.data;
        /**提交后台的请求参数 */
        let reqData = {
            have_base: data.have_base
        };
        reqData.auth_type = data.have_type
        // data.catIdArr.length ? reqData.cate_id = data.catIdArr.join(',') : errorTip += '请选择供应品种' + "\n";

        data.catIdArr.length ? reqData.auth_data = data.catIdArr : errorTip += '请选择供应品种' + "\n";

        data.warehouse.wh_id ? reqData.wh_id = data.warehouse.wh_id : errorTip += '请选择仓库分仓' + "\n";
        data.com_title ? reqData.com_title = data.com_title : errorTip += '请填写公司名称' + "\n";
        data.contact ? reqData.contact = data.contact : errorTip += '请填写联系人' + "\n";
        data.mobile ? reqData.mobile = data.mobile : errorTip += '请填写联系电话' + "\n";
        data.id_photo_front.state == 'ok' ? reqData.id_photo_front = data.id_photo_front.photo : errorTip += '请上传身份证正面' + "\n";
        data.id_photo_back.state == 'ok' ? reqData.id_photo_back = data.id_photo_back.photo : errorTip += '请上传身份证反面' + "\n";
        // data.have_base&&!data.base_video.state!='ok' ? : 
        if (data.have_base) {
            if (data.base_video.state == 'loading') {
                errorTip += '请等待视频上传完成' + "\n";
            } else {
                data.base_video.state == 'ok' ? reqData.base_video = data.base_video.video : errorTip += '请上传基地视频' + "\n";
            }
        }
        //  console.log(data.have_base,data.base_video,data.have_base&&!data.base_video.state!='ok' );
        if (errorTip) {
            console.log("data", data)
            return wx.showModal({
                content: errorTip,
                showCancel: false,
                title: '提示',
            })
        };
        reqData.years = 1
        data.account_photo.state == 'ok' ? reqData.account_photo = data.account_photo.photo : '';

        reqData.com_title = util.replaceStr(reqData.com_title)
        reqData.contact = util.replaceStr(reqData.contact)
        reqData.mobile = util.replaceStr(reqData.mobile)


        console.log("提价的数据", reqData)
        var that = this
        wx.showModal({
            content: '租期为1年，请确定是否申请',
            showCancel: true,
            title: '提示',
            success(res) {
                if (res.confirm) {
                    console.log('用户点击确定')
                    that.combineNew(reqData)
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }

            }
        })

        // console.log("submitBtn_click", this.data.com_title);
    },
    combineNew(reqData) {
        this.request({
            // url: this.data.host + '/home/supplier/combine',
            url: this.data.host + "/home/supplier/combineNew",
            data: reqData,
            method: "POST",
        }, res => {
            if (this.data.tenancy_status == 1) { //支付
                this.request({
                    url: this.data.host + "/home/payment/order",
                    method: "post",
                    data: {
                        order_id: res.data.order_id,
                        code: this.data.pay
                    }
                }, res => {
                    if (this.data.pay == "allin") {
                        //通联支付
                        var payInfo = res.data.payInfo
                        if (payInfo) {
                            payInfo = JSON.parse(payInfo)
                            wx.requestPayment({
                                ...payInfo,
                                success(res) {
                                    wx.showModal({
                                        content: '支付成功，请耐心等待审核',
                                        showCancel: false,
                                        title: '提示',
                                        success(obj) {
                                            wx.navigateBack({
                                                delta: 1,
                                            })
                                        }
                                    })
    
                                },
                                fail(err) {
                                    wx.showToast({
                                        title: '支付失败',
                                        icon: 'none'
                                    })
                                    console.error('pay fail', err)
                                }
                            })
                        }else if(res.data.extraData){//跳转收银台小程序
                            var extraData=res.data.extraData
        
                            this.alinePay(extraData,this.pay_ok)
        
                        }else{
                            wx.showToast({
                              title: '支付失败',
                              icon:"none"
                            })
                        }
                        
                    } else if (this.data.pay == "wxpay") {
                        wx.requestPayment({
                            ...res.data.pay_data,
                            success(res) {
                                wx.showModal({
                                    content: '支付成功，请耐心等待审核',
                                    showCancel: false,
                                    title: '提示',
                                    success(obj) {
                                        wx.navigateBack({
                                            delta: 1,
                                        })
                                    }
                                })

                            },
                            fail(err) {
                                wx.showToast({
                                    title: '支付失败',
                                    icon: 'none'
                                })
                            }
                        })
                    }else{
                        wx.showModal({
                            content: '支付成功，请耐心等待审核',
                            showCancel: false,
                            title: '提示',
                            success(obj) {
                                wx.navigateBack({
                                    delta: 1,
                                })
                            }
                        })
                    }

                })
            } else {
                wx.showModal({
                    content: '提交成功，请耐心等待审核',
                    showCancel: false,
                    title: '提示',
                    success(obj) {
                        wx.navigateBack({
                            delta: 1,
                        })
                    }
                })
            }

        });
    },
    pay_ok(){
        wx.showModal({
            content: '支付成功，请耐心等待审核',
            showCancel: false,
            title: '提示',
            success(obj) {
                wx.navigateBack({
                    delta: 1,
                })
            }
        })
    },
    type_change(e) {
        let val = parseInt(e.currentTarget.dataset.val);
        if (val == this.data.have_type) {
            return
        }
        this.setData({
            have_type: val,
            totalPrice: 0,
            catVal: "请选择品种分类或者产品"
        });
    },
    //查询是否需要供应租金
    getTenancy() {
        this.request({
            url: this.data.host + "/home/supplier/tenancy",
        }, res => {
            //开启租赁收费[0:未开启,1:已开启]
            this.setData({
                tenancy_status: res.data.tenancy_status
            })
        })
    },





    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },



    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})